package com.example.nio.tranport.mina.server;

import com.example.nio.message.Request;
import com.example.nio.message.Response;
import com.example.nio.tranport.mina.factory.MinaServerFactory;
import com.example.nio.tranport.mina.handler.RequestHandler;
import lombok.Data;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;

/**
 * @author: chentao
 * @data 2025年02月02日 下午7:56
 */
@Data
public class MinaServerFactoryImpl extends IoHandlerAdapter implements MinaServerFactory, InitializingBean, DisposableBean {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${mina.server.port:8000}")
    private int port;

    private MinaServer minaServer;

    private RequestHandler requestHandler;

    @Override
    public void afterPropertiesSet() throws Exception {
        this.minaServer = new MinaServer(port, this);
        this.minaServer.init();
        this.minaServer.start();
    }

    @Override
    public void destroy() throws Exception {
        this.minaServer.stop();
    }

    /***
     * 处理请求
     *
     * @param session The session that is receiving a message
     * @param message The received message
     * @throws Exception
     */
    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        if (message instanceof Request) {
            Response response = this.handleRequest((Request) message);
            session.write(response);
        }
    }

    /****
     * 处理请求
     *
     * @param request
     * @return
     */
    @Override
    public Response handleRequest(Request request) {
        return requestHandler.handleRequest(request);
    }
}
